package network;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;

public class FileConnection {
    private static RandomAccessFile logFile;
    private static RandomAccessFile errorFile;

    public static void loadFile() {
        try {
            logFile = new RandomAccessFile(Configuration.getHistoryFileName(), "rw");
            logFile.skipBytes((int) logFile.length());
            errorFile = new RandomAccessFile(Configuration.getErrorFileName(), "rw");
            errorFile.skipBytes((int) errorFile.length());
        } catch (FileNotFoundException e) {
            System.err.println("Could not open logFile");
        } catch (IOException e) {
            System.err.println("Skipp failed");
        }
    }

    public static void log_write(String message) throws IOException {
        synchronized (logFile) {
            logFile.write((message + "\n").getBytes());
        }
    }

    public static void error_write(String message) throws IOException {
        synchronized (errorFile) {
            errorFile.write((new Date() + "> " + message + "\n").getBytes());
        }
    }

    public static String getHistory() throws IOException {
        synchronized (logFile) {
            int mark = (int) logFile.length();
            logFile.seek(0);
            byte[] history = new byte[mark];
            logFile.readFully(history, 0, mark);
            return (new String(history, "UTF-8"));
        }
    }
}
